package com.qiantu.phone.ui.activity;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.swipelayout.SimpleSwipeListener;
import com.hjq.widget.swipelayout.SwipeLayout;
import com.hjq.widget.swipelayout.adapters.RecyclerSwipeAdapter;
import com.huawei.secure.android.common.util.LogsUtil;
import com.qiantu.api.entity.LoginBean;
import com.qiantu.api.entity.UserInfoBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.exception.ResultException;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.FileUtils;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;

import java.util.List;

import okhttp3.Call;

//账号切换
public class ChangeAccountActivity extends AppActivity {

    private RecyclerView mList;
    private AccountAdapter accountAdapter;
    private List<LoginBean> mAccounts;
    private BaseDialog coverDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_change_account;
    }

    @Override
    protected void initView() {
        mList = findViewById(R.id.list);
        mList.setLayoutManager(new LinearLayoutManager(getContext()));
    }

    @Override
    protected void initData() {
        mAccounts = AppApplication.getInstance().getAccounts();
        accountAdapter = new AccountAdapter();
        mList.setAdapter(accountAdapter);
    }

    @Override
    public void onRightClick(View view) {
        super.onRightClick(view);
        LoginActivity.startFromChangeAccount(getAppActivity(), true);
    }

    private class AccountAdapter extends RecyclerSwipeAdapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.account_item_ly, parent, false);
            return new AccountItemViewHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int pp) {
            LoginBean item = mAccounts.get(pp);
            AccountItemViewHolder accountItemViewHolder = (AccountItemViewHolder) viewHolder;
            accountItemViewHolder.setAccountInfo(item);
            //滑动删除用户
            accountItemViewHolder.mDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    coverDialog = new ConfirmCancelHintDialog.Builder(getContext())
                            .setContent(R.string.delete_account_hint)
                            .setRightText(R.string.ok)
                            .setRightBtnBackground(R.drawable.btn_theme_round_4dp)
                            .setListener(new ConfirmCancelHintDialog.OnListener() {
                                @Override
                                public void onLeftClick(BaseDialog dialog) {}

                                @Override
                                public void onRightClick(BaseDialog dialog) {
                                    mItemManger.closeAllItems();
                                    mAccounts.remove(viewHolder.getAbsoluteAdapterPosition());
                                    FileUtils.saveAccounts(getContext(), mAccounts);
                                    AccountAdapter.this.notifyDataSetChanged();
                                }
                            })
                            .create();
                    coverDialog.show();
                }
            });
            //item点击切换方法
            accountItemViewHolder.mItemLy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItemManger.closeAllItems();
                    LoginBean bean = mAccounts.get(viewHolder.getAbsoluteAdapterPosition());
                    if (!bean.getUserInfo().getUserSerialNo().equals(AppApplication.getInstance().getLoginInfo().getUserInfo().getUserSerialNo())){
                        LogsUtil.i("66666----",""+pp+"----"+viewHolder.getAbsoluteAdapterPosition());
                        changeAccount(viewHolder.getAbsoluteAdapterPosition());
                    }
                }
            });
            accountItemViewHolder.swipeLayout.addSwipeListener(new SimpleSwipeListener(){
                @Override
                public void onOpen(SwipeLayout layout) {
                    mItemManger.closeAllExcept(layout);
                    accountItemViewHolder.setIsRecyclable(false);
                }

                @Override
                public void onClose(SwipeLayout layout) {
                    accountItemViewHolder.setIsRecyclable(true);
                }
            });

            mItemManger.bind(accountItemViewHolder.itemView, pp);
        }

        @Override
        public int getItemCount() {
            if (mAccounts == null)
                return 0;
            return mAccounts.size();
        }

        @Override
        public int getSwipeLayoutResourceId(int position) {
            return R.id.swipe_layout;
        }
    }

    private void changeAccount(int position) {
        LoginBean loginBean = mAccounts.get(position);
        LLHttpManager.getUserInfo(getAppActivity(), loginBean, new HttpCallback<HttpData<UserInfoBean>>(getAppActivity()){
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.changing_account));
            }

            @Override
            public void onSucceed(HttpData<UserInfoBean> result) {
                super.onSucceed(result);
                loginBean.setUserInfo(result.getData());
                AppApplication.getInstance().changeAccount(getAppActivity(), loginBean);
            }

            @Override
            public void onFail(Exception e) {
                if (e instanceof ResultException){
                    int errorCode = ((ResultException)e).getHttpData().getCode();
                    if (errorCode == 10401 //用户未登录或登录状态已过期
                            || errorCode == 90010
                            || errorCode == 90007){
                        toast(R.string.logint_invalid);
                        mAccounts.remove(position);
                        FileUtils.saveAccounts(getContext(), mAccounts);
                        accountAdapter.notifyDataSetChanged();
                    }else {
                        super.onFail(e);
                    }
                }else {
                    super.onFail(e);
                }
            }
        });
    }

    class AccountItemViewHolder extends RecyclerView.ViewHolder {
        private LinearLayout mDelete;
        private ImageView mImage;
        private TextView mName;
        private TextView mPhone;
        private View mCheck;
        private SwipeLayout swipeLayout;
        private View mItemLy;

        public AccountItemViewHolder(@NonNull View itemView) {
            super(itemView);
            mDelete = itemView.findViewById(R.id.delete);
            mImage = itemView.findViewById(R.id.image);
            mName = itemView.findViewById(R.id.name);
            mPhone = itemView.findViewById(R.id.phone);
            mCheck = itemView.findViewById(R.id.check);
            swipeLayout = itemView.findViewById(R.id.swipe_layout);
            mItemLy = itemView.findViewById(R.id.item_ly);
        }

        public void setAccountInfo(LoginBean item) {
            GlideApp.with(getContext())
                    .load(item.getUserInfo().getAvatar())
                    .placeholder(mImage.getDrawable())
                    .error(mImage.getDrawable())
                    .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                    .into(mImage);
            mName.setText(item.getUserInfo().getNickName());
            mPhone.setText(item.getUserInfo().getPhone());
            if (AppApplication.getInstance().getLoginInfo().getUserInfo().getUserSerialNo().equals(item.getUserInfo().getUserSerialNo())){
                mCheck.setSelected(true);
                swipeLayout.setSwipeEnabled(false);
            }else {
                swipeLayout.setSwipeEnabled(true);
                mCheck.setSelected(false);
            }
        }
    }
}